package com.example.travelexpensemanager;

import java.math.BigInteger;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class Purpose extends Activity {

	EditText etPurpose, etAmount;
	Spinner spnPayingMember;
	Button btnSubmit,btnAddDateTimeToPurpose;
	ArrayAdapter<String> adapter;
	DatabaseOperations databaseOperations;
	ArrayList<String> memberNames;
	ArrayList<String> memberTableAmount;
	String titleToBeReplaced;
	/* Size for the account */
	BigInteger accountTotalSize;
	/* The amount table for amount */
	BigInteger amountTableAmount;
	/* Average for the above amount */
	BigInteger averageOfAmount;
	/* Get all the members in an arraylist */
	ArrayList<String> memberList;
	/* Get all the amounts paid by every member */
	ArrayList<String> memberAmounts;
	/*
	 * Attributes object is having all the details of the text fields as it had
	 * to be entered in to the database
	 */
	ArrayList<String> attributes;
	AlertDialog alertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.purpose);

		/*
		 * Attributes object is having all the details of the text fields as it
		 * had to be entered in to the database
		 */
		attributes = new ArrayList<String>();

		/* Linking the textfields to their Ids */
		etPurpose = (EditText) findViewById(R.id.etPurpose);
		etAmount = (EditText) findViewById(R.id.etAmount);

		/* Creating an object of database operations */
		databaseOperations = new DatabaseOperations(this);

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		/*
		 * Creating an arraylist of members so that in this all the meber names
		 * come
		 */
		memberNames = new ArrayList<String>();
		memberNames = databaseOperations.retrieveAll(
				DatabaseOperations.getMembertable(),
				new String[] { DatabaseOperations.getMembertablemember() },
				DatabaseOperations.getMembertabletitle() + "=" + "\""
						+ SessionClass.sessionObject().getTitle() + "\"", null,
				null, null, null);

		/* Closing the database */
		databaseOperations.closeDatabase();

		if (memberNames.size() == 0) {
			Toast.makeText(getApplicationContext(),
					"At least one member should be added to the account",
					Toast.LENGTH_SHORT).show();
			finish();
		}

		/* Initialising the dropdown box */
		spnPayingMember = (Spinner) findViewById(R.id.spnPayingMember);

		/*
		 * Initialising the adapter with the arraylist so that the drop down
		 * list can have the list of all the members belonging to that title
		 */
		adapter = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_spinner_item, memberNames);

		/* Adding the arraylist to the dropdown box */
		spnPayingMember.setAdapter(adapter);

		/* Initialising the button */
		btnSubmit = (Button) findViewById(R.id.btnSubmit);

		btnSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(Purpose.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}
				

				/* Opening the database */
				databaseOperations.openWriteableDatabase();

				if (etPurpose.getText().toString().equals("")
						&& etAmount.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(), "Fields are Empty",
							Toast.LENGTH_SHORT).show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}

				if (etPurpose.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(),
							"Purpose Field is Empty", Toast.LENGTH_SHORT)
							.show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}

				if (etAmount.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(),
							"Amount Field is Empty", Toast.LENGTH_SHORT).show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}
				/*
				 * Adding all the text field values from the screen to put into
				 * the database
				 */
				attributes.add(SessionClass.sessionObject().getTitle());
				attributes.add(spnPayingMember.getSelectedItem().toString());
				attributes.add(etPurpose.getText().toString());
				attributes.add(etAmount.getText().toString());
				/***************************************************/
				System.out.println(attributes.size());
				long x = databaseOperations.insertIntoTable(
						DatabaseOperations.getPurposetable(),
						new String[] {
								DatabaseOperations.getPurposetabletitle(),
								DatabaseOperations
										.getPurposetablepayingmember(),
								DatabaseOperations.getPurposetablepurpose(),
								DatabaseOperations.getPurposetableamount() },
						attributes);

				if (x == -1) {
					Toast.makeText(
							getApplicationContext(),
							spnPayingMember.getSelectedItem().toString()
									+ " has already paid for "
									+ etPurpose.getText().toString(),
							Toast.LENGTH_SHORT).show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					/*
					 * Reinitializing the variables hatever were declared inside
					 * that button
					 */
					attributes = new ArrayList<String>();
					return;
				} else {
					/*
					 * If the row is inserted then we need to update the amount
					 * for the member
					 */
					/* For that first retrieve the value */
					BigInteger  amount = new BigInteger(databaseOperations.retrieve(
							DatabaseOperations.getMembertable(),
							new String[] { DatabaseOperations
									.getMembertableamount() },
							DatabaseOperations.getMembertabletitle()
									+ "="
									+ "\""
									+ SessionClass.sessionObject().getTitle()
									+ "\" and "
									+ DatabaseOperations.getMembertablemember()
									+ "="
									+ "\""
									+ spnPayingMember.getSelectedItem()
											.toString() + "\"", null, null,
							null, null));

					/* Now need to update the amount with new value */
					amount = amount.add((new BigInteger(etAmount.getText().toString())));
					/* Now we need to update the row */
					@SuppressWarnings("unused")
					int updatedRows = databaseOperations.updateRow(
							DatabaseOperations.getMembertable(),
							DatabaseOperations.getMembertableamount(),
							String.valueOf(amount),
							DatabaseOperations.getMembertabletitle()
									+ "="
									+ "\""
									+ SessionClass.sessionObject().getTitle()
									+ "\" and "
									+ DatabaseOperations.getMembertablemember()
									+ "="
									+ "\""
									+ spnPayingMember.getSelectedItem()
											.toString() + "\"", null);

					/* Updating the amount in the amount table */
					memberTableAmount = new ArrayList<String>();
					/* retrieving all the titles */
					memberTableAmount = databaseOperations.retrieveAll(
							DatabaseOperations.getMembertable(),
							new String[] { DatabaseOperations
									.getMembertableamount() },
							DatabaseOperations.getMembertabletitle() + "=\""
									+ SessionClass.sessionObject().getTitle()
									+ "\"", null, null, null, null);

					amount = new BigInteger("0");
					/* Adding all the amounts */
					for (String str : memberTableAmount) {
						amount = amount.add((new BigInteger(str)));
					}

					databaseOperations.updateRow(
							DatabaseOperations.getAmounttable(),
							DatabaseOperations.getAmounttableamount(),
							String.valueOf(amount),
							DatabaseOperations.getAmounttabletitle() + "=\""
									+ SessionClass.sessionObject().getTitle()
									+ "\"", null);

					/* Updating the toGet column in the Member Table */
					updateToGetAndToGiveColumns();

					/* Closing the database */
					databaseOperations.closeDatabase();
					finish();
					return;
				}
			}
		});
		
		btnAddDateTimeToPurpose=(Button)findViewById(R.id.addDateTimeToPurpose);
		btnAddDateTimeToPurpose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialogBoxAddDateTime("Add Date and Time",
						"Do you want to add date and time to the purpose");				
			}
		});
	}
	
	/* Adding a date and time in account */
	private void showDialogBoxAddDateTime(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		dialogBuilder.setPositiveButton("Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						if (etPurpose.getText().length() == 0) {
							etPurpose.setText(Utils.getCurrentDate() + " "
									+ Utils.getCurrentTime());
						} else {
							titleToBeReplaced = etPurpose.getText().toString()
									.replaceAll("\\s+", " ");
							titleToBeReplaced = titleToBeReplaced + " : "
									+ Utils.getCurrentDate() + " " + Utils.getCurrentTime();
							etPurpose.setText(titleToBeReplaced);
						}
						/* Set cursor at the end */
						etPurpose.setSelection(etPurpose.getText().length());
					}
				});
		dialogBuilder.setNegativeButton("Don't Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	public void updateToGetAndToGiveColumns() {
		/* Retrieve the size of the Amount Table */
		accountTotalSize = new BigInteger(databaseOperations.retrieve(DatabaseOperations
						.getAmounttable(), new String[] { DatabaseOperations
						.getAmounttabletotalmembers() },
						DatabaseOperations.getAmounttabletitle() + "=\""
								+ SessionClass.sessionObject().getTitle()
								+ "\"", null, null, null, null));

		/* Retrieve the amount table amount */
		amountTableAmount = new BigInteger(databaseOperations.retrieve(
				DatabaseOperations.getAmounttable(),
				new String[] { DatabaseOperations.getAmounttableamount() },
				DatabaseOperations.getAmounttabletitle() + "=\""
						+ SessionClass.sessionObject().getTitle() + "\"", null,
				null, null, null));
		/* Calculating the average */
		averageOfAmount = amountTableAmount.divide(accountTotalSize);

		/* Retrieving all the members of the particular account */
		memberList = databaseOperations.retrieveAll(
				DatabaseOperations.getMembertable(),
				new String[] { DatabaseOperations.getMembertablemember() },
				DatabaseOperations.getMembertabletitle() + "=\""
						+ SessionClass.sessionObject().getTitle() + "\"", null,
				null, null, null);

		/* Retrieving all the amounts of the particular accounts */
		memberAmounts = databaseOperations.retrieveAll(
				DatabaseOperations.getMembertable(),
				new String[] { DatabaseOperations.getMembertableamount() },
				DatabaseOperations.getMembertabletitle() + "=\""
						+ SessionClass.sessionObject().getTitle() + "\"", null,
				null, null, null);

		for (int i = 0; i < accountTotalSize.intValue(); i++) {
			/*
			 * Suppose a person has given more then he has to receive from his
			 * friends
			 */
			if ((new BigInteger(memberAmounts.get(i))).intValue() > averageOfAmount.intValue()) {
				/* Updating the to get column */
				databaseOperations.updateRow(
						DatabaseOperations.getMembertable(),
						DatabaseOperations.getMembertabletoget(),
						String.valueOf((new BigInteger(memberAmounts.get(i))).intValue()
								- averageOfAmount.intValue()),
						DatabaseOperations.getMembertabletitle() + "=" + "\""
								+ SessionClass.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations.getMembertablemember()
								+ "=" + "\"" + memberList.get(i) + "\"", null);

				databaseOperations.updateRow(
						DatabaseOperations.getMembertable(),
						DatabaseOperations.getMembertabletogive(),
						String.valueOf(0),
						DatabaseOperations.getMembertabletitle() + "=" + "\""
								+ SessionClass.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations.getMembertablemember()
								+ "=" + "\"" + memberList.get(i) + "\"", null);
			}
			/*
			 * Suppose a person has given less then he has to give to his
			 * friends
			 */
			else if ((new BigInteger(memberAmounts.get(i))).intValue() < averageOfAmount.intValue()) {
				/* Updating the to get column */
				databaseOperations.updateRow(
						DatabaseOperations.getMembertable(),
						DatabaseOperations.getMembertabletogive(),
						String.valueOf(averageOfAmount.intValue()
								- (new BigInteger(memberAmounts.get(i))).intValue()),
						DatabaseOperations.getMembertabletitle() + "=" + "\""
								+ SessionClass.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations.getMembertablemember()
								+ "=" + "\"" + memberList.get(i) + "\"", null);

				databaseOperations.updateRow(
						DatabaseOperations.getMembertable(),
						DatabaseOperations.getMembertabletoget(),
						String.valueOf(0),
						DatabaseOperations.getMembertabletitle() + "=" + "\""
								+ SessionClass.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations.getMembertablemember()
								+ "=" + "\"" + memberList.get(i) + "\"", null);
			}
		}
	}
}
